package com.utils;

import java.util.ArrayList;
import java.util.List;

public class PhaseUtil {

    private static List<Integer> havePhaseValueList = new ArrayList();

    /**
     * 相位检测工具
     *
     * @param phaseBinary
     * @return
     */
    public static boolean checkPhase(String phaseBinary) {
        havePhaseValueList.clear();
        char[] phaseChar = phaseBinary.toCharArray();
        Integer oneFirstPosition = null;

        //记录第一位是否有相位值1  和 记录所有有相位值得位置
        for (int i = 0; i < phaseChar.length; i++) {
            String str = String.valueOf(phaseChar[i]);
            if ("1".equals(str)) {
                havePhaseValueList.add(i);
                if (oneFirstPosition == null) {
                    oneFirstPosition = i;
                }
            }
        }

        //如果本次数据没相位值则本次失败
        if (havePhaseValueList.size() <= 0) {
            return false;
        }

        //如果本次只有一个相位值算成功
        if (havePhaseValueList.size() == 1) {
            return true;
        }

        //如果没记录到首位的位置则失败
        if (oneFirstPosition == null) {
            return false;
        }

        //如果本次数据第一位没有数据 则接下去的数据只要有不连续的话则算失败
        if (oneFirstPosition != 0) {
            int continueValue = 0;
            for (int i = 0; i < havePhaseValueList.size() - 1; i++) {
                if ((havePhaseValueList.get(i + 1) - havePhaseValueList.get(i)) == 1) {
                    continueValue++;
                } else {
                    return false;
                }
            }

            //如果是连续1~5之前则成功
            if (continueValue >= 1 && continueValue <= 5) {
                return true;
            }
        }

        //如果第一位是0 则前面累加并开始倒叙值是否连续 连续则成功 否则失败
        if (oneFirstPosition == 0) {
            int continueValue = 1;
            for (int i = 0; i < havePhaseValueList.size() - 1; i++) {
                if ((havePhaseValueList.get(i + 1) - havePhaseValueList.get(i)) == 1) {
                    continueValue++;
                } else if (havePhaseValueList.get(i + 1) >= (15 - 4 + continueValue)) {
                    int len = 16 - havePhaseValueList.get(i + 1);
                    int jv = 0;
                    for (int k = 0; k < havePhaseValueList.size(); k++) {
                        if (havePhaseValueList.get(k) >= havePhaseValueList.get(i + 1)) {
                            jv++;
                        }
                    }
                    if (jv == len) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            //如果是连续1~5之前则成功
            if (continueValue >= 1 && continueValue <= 5) {
                return true;
            }
        }

        return false;
    }
}
